/* USER CODE BEGIN Header */
/**
 ******************************************************************************
 * @file           : main.c
 * @brief          : Main program body
 ******************************************************************************
 * @attention
 *
 * Copyright (c) 2025 STMicroelectronics.
 * All rights reserved.
 *
 * This software is licensed under terms that can be found in the LICENSE file
 * in the root directory of this software component.
 * If no LICENSE file comes with this software, it is provided AS-IS.
 *
 ******************************************************************************
 */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "dma.h"
#include "spi.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
extern DMA_HandleTypeDef hdma_usart1_rx;
extern DMA_HandleTypeDef hdma_usart1_tx;

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  // 1ms周期
  if (htim == &htim6)
  {
    tim6_count++;
    hcsr04_count++;

    // 5ms任务：每5ms执行一次
    if (tim6_count % 5 == 0)
    {
      // 调用 5ms 任务处理函数
      get_imu_data(&imu963);
      attitude(&imu963);
    }

    // 10ms任务：每10ms执行一次
    if (tim6_count % 10 == 0)
    {
      // 调用 10ms 任务处理函数
    }

    // 15ms任务：每15ms执行一次
    if (tim6_count % 10 == 0)
    {
      // 调用 15ms 任务处理函数
    }
    if (tim6_count % 1000 == 0)
    {
      // 调用 1s 任务处理函数
      OLED_ShowNum(32, 56, tim6_count / 1000, 3, OLED_6X8);
    }

    // 防止计数器溢出（1000s清空一次）
    if (tim6_count >= 1000000)
    {
      tim6_count = 0;
    }
    //  hhSerial_Printf("x:,%d,y:%d,z:%d\n", imu963ra_mag_x, imu963ra_mag_y, imu963ra_mag_z);
    //  Madgwick_9_DOF_Get_Angle(IMU963RA, 5);
  }
}
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
  if (huart == &huart1)
  {
    Serial_RxFlag = 1;
    Serial_Control();
    Serial_Rxdate[Size] = '\0';
    // Serial_Control();

    HAL_UARTEx_ReceiveToIdle_DMA(&huart1, Serial_Rxdate, sizeof(Serial_Rxdate));
    __HAL_DMA_DISABLE_IT(&hdma_usart1_rx, DMA_IT_HT);
  }
}
/* USER CODE END 0 */

/**
 * @brief  The application entry point.
 * @retval int
 */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_SPI2_Init();
  MX_TIM6_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */
  OLED_Init();
  OLED_Update();
  HAL_UARTEx_ReceiveToIdle_DMA(&huart1, Serial_Rxdate, sizeof(Serial_Rxdate));
  __HAL_DMA_DISABLE_IT(&hdma_usart1_rx, DMA_IT_HT);
  uint8_t id = IMU_ReadID();
  OLED_ShowHexNum(6, 56, id, 4, OLED_6X8);
  imu963ra_init();
  get_imu_offset(&imu963);
  // IMU_Offset_Init(IMU963RA);
  HAL_TIM_Base_Start_IT(&htim6); // 启动时基
                                 // OLED_ShowString(6, 8, "pitch:", OLED_6X8);
                                 // OLED_ShowString(6, 24, "roll:", OLED_6X8);
                                 // OLED_ShowString(6, 40, "yaw:", OLED_6X8);

  // hhSerial_Printf("hello,%s\n", "world");

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */

  while (1)
  {

    // float des = sonar();
    // OLED_ShowFloatNum(6, 8, sonar(), 2, 2, OLED_6X8);

    // OLED_ShowFloatNum(42, 8, (float)imu963.pitch, 3, 2, OLED_6X8);
    // OLED_ShowFloatNum(42, 24, (float)imu963.roll, 3, 2, OLED_6X8);
    // OLED_ShowFloatNum(42, 40, (float)imu963.yaw, 3, 2, OLED_6X8);

    // 显示原始数据，用来调节量程

    // OLED_ShowSignedNum(50, 8, imu963ra_acc_x, 5, OLED_6X8);
    // OLED_ShowSignedNum(50, 24, imu963ra_acc_y, 5, OLED_6X8);
    // OLED_ShowSignedNum(50, 40, imu963ra_acc_z, 5, OLED_6X8);

    // OLED_ShowSignedNum(1, 8, imu963ra_gyro_x, 5, OLED_6X8);
    // OLED_ShowSignedNum(1, 24, imu963ra_gyro_y, 5, OLED_6X8);
    // OLED_ShowSignedNum(1, 40, imu963ra_gyro_z, 5, OLED_6X8);

    // OLED_ShowSignedNum(90, 8, imu963ra_mag_x, 5, OLED_6X8);
    // OLED_ShowSignedNum(90, 24, imu963ra_mag_y, 5, OLED_6X8);
    // OLED_ShowSignedNum(90, 40, imu963ra_mag_z, 5, OLED_6X8);

    //
    // OLED_ShowFloatNum(1, 8, imu963.acc_real[0], 2, 2, OLED_6X8);
    // OLED_ShowFloatNum(1, 24, imu963.acc_real[1], 2, 2, OLED_6X8);
    // OLED_ShowFloatNum(1, 40, imu963.acc_real[2], 2, 2, OLED_6X8);

    // OLED_ShowFloatNum(60, 8, imu963.gyro_real[0], 2, 2, OLED_6X8);
    // OLED_ShowFloatNum(60, 24, imu963.gyro_real[1], 2, 2, OLED_6X8);
    // OLED_ShowFloatNum(60, 40, imu963.gyro_real[2], 2, 2, OLED_6X8);

    // OLED_ShowFloatNum(36, 56, factor_gyro_lvbo, 1, 4, OLED_6X8);
    // OLED_ShowNum(86, 56, Serial_Rxdate[0], 1, OLED_6X8);

    OLED_Update();
    // HAL_Delay(500);
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
 * @brief System Clock Configuration
 * @retval None
 */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
   */
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** Initializes the RCC Oscillators according to the specified parameters
   * in the RCC_OscInitTypeDef structure.
   */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLM = 8;
  RCC_OscInitStruct.PLL.PLLN = 168;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 4;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
   */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
 * @brief  This function is executed in case of error occurrence.
 * @retval None
 */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef USE_FULL_ASSERT
/**
 * @brief  Reports the name of the source file and the source line number
 *         where the assert_param error has occurred.
 * @param  file: pointer to the source file name
 * @param  line: assert_param error line source number
 * @retval None
 */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
